// src/utils/request.js
import axios from 'axios'

const baseURL = `${window.location.protocol}//${window.location.hostname}:8080`;

const request = axios.create({
  baseURL,
  timeout: 10000,
})

// 请求拦截器：在每次请求前自动加上 Token
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')

    // 登录和注册接口不带 token
    if (token && !(config.url.includes('/api/auth/login') || config.url.includes('/api/auth/register'))) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 自动加 Content-Type
    if (config.method.toUpperCase() === 'POST' && !config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json'
    }

    // 调试输出
    console.log('[请求调试信息]')
    console.log('方法:', config.method.toUpperCase())
    console.log('URL:', config.baseURL + config.url)
    console.log('请求头:', config.headers)
    if (config.data) console.log('请求体:', config.data)

    return config
  },
  (error) => Promise.reject(error)
)


// ✅ 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('请求失败:', error)
    return Promise.reject(error)
  }
)

export default request
